﻿using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Boms.Commands;

/// <summary>
/// 创建工序 BOM 命令。
/// </summary>
public record CreateBomCommand(ProcBomDto Bom) : IRequest<IResult<bool>>;

internal sealed class CreateBomCommandHandler(IRepository<ProcBom> repo) : IRequestHandler<CreateBomCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateBomCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.OpId == request.Bom.OpId && m.MaterialCode == request.Bom.MaterialCode, cancellationToken))
        {
            return Result.Failure("工序BOM已存在");
        }

        var bom = request.Bom.Adapt<ProcBom>();
        var ok = await repo.InsertAsync(bom, cancellationToken);
        return Result.From(ok);
    }
}
